/*
 * @Author: your name
 * @Date: 2021-05-28 15:46:32
 * @LastEditTime: 2021-05-28 17:11:21
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_music_api\utils\callCloudStorage.js
 */
const { getAccessToken } = require('../utils/getAccessToken.js')
const { default: axios } = require('axios')
const rp = require('request-promise')
const fs = require('fs')

const callCloudStorage = {
  async download(ctx, fileList) {
      const access_token = await getAccessToken()
      const url = `https://api.weixin.qq.com/tcb/batchdownloadfile?access_token=${access_token}`
      try {
          const result = await axios.post(url, { 
              env: ctx.state.env,
              file_list: fileList
            })
            console.log('result', result.data)
          return result
      } catch (err) {
          console.log('ACCESS_TOKEN,err', err)
      }
  },
  async upload(ctx){
    // 1.请求地址
    const access_token = await getAccessToken()
    const file = ctx.request.files.file
    const url = `https://api.weixin.qq.com/tcb/uploadfile?access_token=${access_token}`
    const path = `swiper/${Date.now()}-${Math.random()}-${file.name}`
    try {
      const result = await axios.post(url, {
        env: ctx.state.env,
        path
      })
      const fileData = result.data
      // 2、上传图片
      const params = {
        method: 'POST',
        headers: {
          'content-type': 'multipart/form-data'
        },
        uri: fileData.url,
        formData: {
          'key': path,
          'Signature': fileData.authorization,
          'x-cos-security-token': fileData.token,
          'x-cos-meta-fileid': fileData.cos_file_id,
          'file': fs.createReadStream(file.path)
        },
        json: true
      }
      await rp(params)
      return fileData.file_id
    } catch (err) {
      console.log('ACCESS_TOKEN,err', err)
    }
  },
  async delete(ctx, fileid_list) {
    const access_token = await getAccessToken()
    const url = `https://api.weixin.qq.com/tcb/batchdeletefile?access_token=${access_token}`
    try {
      const result = await axios.post(url, {
        env: ctx.state.env,
        fileid_list
      })
      return result
    } catch (err) {
      console.log('ACCESS_TOKEN,err', err)
    }
  }
}


module.exports = callCloudStorage
